datacops-cms
Version:
A modern, extensible CMS built with Next.js and Prisma.
61 lines (57 loc) • 1.93 kB
text/typescript
import NextAuth, { NextAuthOptions, Session } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
import bcrypt from "bcryptjs"
import type { JWT } from "next-auth/jwt"
const prisma = new PrismaClient()
const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
session: { strategy: "jwt" },
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null
const user = await prisma.user.findUnique({
where: { email: credentials.email }
})
if (!user) return null
const valid = await bcrypt.compare(credentials.password, user.password)
if (!valid) return null
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role, // <--- this is fine, not affecting AdapterUser type
avatar: user.avatar || "", // Ensure avatar is always a string
}
}
})
],
callbacks: {
async session({ session, token }: { session: Session; token: JWT }) {
if (session.user) {
session.user.id = token.sub as string
session.user.role = (token.role as "SUPERADMIN" | "ADMIN" | "USER") || "USER"
}
return session
},
async jwt({ token, user }) {
if (user) {
// @ts-expect-error custom field, not typed on base JWT
token.role = user.role
}
return token
}
},
pages: {
signIn: "/login",
}
}
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }